package core

import (
	"fmt"
	"gitee.com/hongzhaomin/gspring/enums"
	"gitee.com/hongzhaomin/gspring/iface"
	"gitee.com/hongzhaomin/gspring/tools"
	"sync"
)

type BeanDefinitionBuilder struct{}

var (
	once     sync.Once
	instance *BeanDefinitionBuilder
)

func NewBeanDefinitionBuilder() *BeanDefinitionBuilder {
	once.Do(func() {
		instance = new(BeanDefinitionBuilder)
	})
	return instance
}

func (BeanDefinitionBuilder) Default(bean any) iface.BeanDefinition {
	tools.Assert().NotNil(bean, "无效的gspring bean: nil值")
	beanKind := enums.GetBeanKindEnum(bean)
	tools.Assert().IsTrue(beanKind.IsValid(),
		fmt.Sprintf("无效的gspring bean, 缺少配置注解: %s", tools.GetFullPathName(bean)))

	// fixme: 不能使用这种方式，如果bean传的是(*Struct)(nil)，这里就会panic
	//rv := reflect.ValueOf(bean)
	//rt := reflect.Indirect(rv).Type()
	rt := tools.IndirectReflectType(bean)

	//var bd iface.BeanDefinition
	//if rv.IsValid() && rv.Kind() == reflect.Ptr && !rv.IsNil() {
	//	bd = NewDefaultBeanDefinitionByObj(bean)
	//} else {
	//	bd = NewDefaultBeanDefinition(rt)
	//}

	beanName := beanKind.ResolveBeanName(rt)
	return NewDefaultBeanDefinition(beanName, rt)
}
